import {
	useStore
} from '@/store/counter.js'

// 基础配置
const baseConfig = {
	// baseURL: 'https://aw2025ht.kangye.xyz/api',
	baseURL: 'http://localhost:8088',
	timeout: 10000,
	header: {
		'Content-Type': 'application/json'
	}
}

// 请求拦截
const requestInterceptor = (config) => {
	const store = useStore()
	const drivertoken = uni.getStorageSync('drivertoken')
	config.header['Authorization'] = `Bearer ${drivertoken}`
	config.header['Authori-zation'] = drivertoken
	console.log(config, 'config')
	return config
}

// 响应拦截
const responseInterceptor = (response) => {
	const {
		statusCode,
		data
	} = response

	// 请求成功
	if (statusCode === 200) {
		if (data.code === 0 || data.code === 200) {
			return data
		} else if (data.code === 401) {
			uni.removeStorageSync('token')
			uni.removeStorageSync('drivertoken')
			uni.removeStorageSync('authStatus')
			uni.removeStorageSync('login_data')
			uni.removeStorageSync('role')
			role
			uni.showToast({
				title: '登录已过期,请重新登录',
				icon: 'none'
			})
			// 跳转登录页
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 500)
			return Promise.reject(response)
		} else {
			// 业务错误
			// uni.showToast({
			// 	title: data.message || '请求失败',
			// 	icon: 'none'
			// })
			return Promise.reject(data)
		}
	}

	// 处理特定错误码
	if (statusCode === 401) {
		// token 过期,清除登录状态
		uni.removeStorageSync('token')
		uni.showToast({
			title: '登录已过期,请重新登录',
			icon: 'none'
		})
		// 跳转登录页
		setTimeout(() => {
			uni.redirectTo({
				url: '/pages/login/login'
			})
		}, 1500)
		return Promise.reject(response)
	}

	// 其他错误
	uni.showToast({
		title: '网络请求失败',
		icon: 'none'
	})
	return Promise.reject(response)
}

// 请求函数
const request = (options = {}) => {
	console.log(options)
	const fullUrl = `${baseConfig.baseURL}${options.url}`
	const lastUrl = options.url
	console.log('Request URL:', fullUrl) // 调试用

	const config = {
		...baseConfig,
		...options,
		lastUrl: lastUrl,
		url: fullUrl,
		header: {
			...baseConfig.header,
			...options.header
		}
	}
	// debugger

	// 请求拦截
	const finalConfig = requestInterceptor(config)

	return new Promise((resolve, reject) => {
		uni.request({
			...finalConfig,
			success: (response) => {
				try {
					resolve(responseInterceptor(response))
				} catch (error) {
					reject(error)
				}
			},
			fail: (error) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
				reject(error)
			}
		})
	})
}

// 封装常用请求方法
export const http = {
	get(url, params = {}, options = {}) {
		return request({
			url,
			method: 'GET',
			data: params,
			...options
		})
	},

	post(url, data = {}, options = {}) {
		return request({
			url,
			method: 'POST',
			data,
			...options
		})
	},

	put(url, data = {}, options = {}) {
		return request({
			url,
			method: 'PUT',
			data,
			...options
		})
	},

	delete(url, data = {}, options = {}) {
		return request({
			url,
			method: 'DELETE',
			data,
			...options
		})
	}
}

// 导出实例
export default http